//
//  HealthViewController.m
//  JiuLe
//
//  Created by 黄鑫 on 16/9/7.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "HealthViewController.h"
#import "HealthSummaryGraphViewController.h"
#import "HealthBreatheViewController.h"
#import "HealthHeartRateViewController.h"
#import "HealthOxygenViewController.h"
#import "HealthTemperatureViewController.h"
#import "HealthSleepingViewController.h"
#import "BaseDataRequest.h"
#import "NSString+Helper.h"
#import "ShareObjectSingleton.h"
#import "MallRequestManager.h"

@interface HealthViewController ()<VRGCalendarViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *labCountsteps;        //计步
@property (weak, nonatomic) IBOutlet UILabel *labHeartrate;         //心率
@property (weak, nonatomic) IBOutlet UILabel *labRespiratoryrate;   //呼吸
@property (weak, nonatomic) IBOutlet UILabel *labSlepp;             //睡眠
@property (weak, nonatomic) IBOutlet UILabel *labOxygensaturation;  //血氧
@property (weak, nonatomic) IBOutlet UILabel *labTemperature;       //体温
@property (weak, nonatomic) IBOutlet UILabel *labDepth;             //深度睡眠
@property (weak, nonatomic) IBOutlet UILabel *labNumber;            //翻身次数
@property (weak, nonatomic) IBOutlet UILabel *labDistance;          //距离
@property (weak, nonatomic) IBOutlet UILabel *labHeat;              //热量
@property (weak, nonatomic) IBOutlet UILabel *labelTime;
@property (strong, nonatomic) NSMutableDictionary *response;
@property (assign, nonatomic) float distance;
@property (assign, nonatomic) float heat;
@property (strong, nonatomic) NSString *selectDate;
@property (nonatomic, strong) VRGCalendarView *pickerView;
@property (nonatomic, strong) UIView *maskView;

@end

@implementation HealthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"健康数据";
    [self showNavgationWithLeftItemWithTitle:@"首页"];
    [self showNavBarWithRightOneImage:[UIImage imageNamed:@"icon_share"] andRightTwoImage:[UIImage imageNamed:@"icon_date"] andRightOneAction:@selector(rightNavButtonClicked:) andRighTwoAction:@selector(setupDateView:)];
    self.labCountsteps.attributedText = [self setLabelText:@"0 步" perUnitLength:1];
    self.labHeartrate.attributedText = [self setLabelText:@"0 次/分" perUnitLength:3];
    self.labRespiratoryrate.attributedText = [self setLabelText:@"0 次/分" perUnitLength:3];
    self.labSlepp.attributedText = [self setLabelText:@"0 小时" perUnitLength:2];
    self.labOxygensaturation.attributedText = [self setLabelText:@"0 %" perUnitLength:1];
    self.labTemperature.attributedText = [self setLabelText:@"0 ℃" perUnitLength:1];
    self.labNumber.text = @"0次";
    self.labDepth.text = @"0小时";
    self.labHeat.text = @"0千卡";
    self.labDistance.text = @"0公里";
    self.selectDate = @"0";
    [self getHealthData];
}

#pragma mark - 数据请求
- (void)getHealthData{
    [SVProgressHUD showWithStatus:@"获取健康数据.." maskType:SVProgressHUDMaskTypeClear];
    [[BaseDataRequest alloc] getHealthData:self.selectDate withBlock:^(id responseObject, NSString *status, NSError *error) {
        if ([status isEqualToString:@"0"]) {
            self.response = [responseObject objectForKey:@"result"];
            NSString *activity = [_response objectForKey:@"activity"];//计步
            NSString *heartRate = [_response objectForKey:@"heart_rate"];//心率
            NSString *breath = [_response objectForKey:@"breath"];//呼吸
            NSString *sleep = [NSString stringWithFormat:@"%.1f", [[_response objectForKey:@"sleep_total_time"] floatValue]/60];//总睡眠
            NSString *spo2 = [_response objectForKey:@"spo2"];//血氧
            NSString *skintemp = [_response objectForKey:@"skintemp"];//体表温度
            float sleepTime = [[_response objectForKey:@"sleep_effective_time"] floatValue];
            NSString *effective = [NSString stringWithFormat:@"%.1f",sleepTime/60];//深度睡眠
            NSString *rover = [_response objectForKey:@"sleep_rover_time"];//翻身次数
            self.labCountsteps.attributedText = [self setLabelText:[NSString stringWithFormat:@"%@ 步",activity] perUnitLength:1];
            self.labHeartrate.attributedText = [self setLabelText:[NSString stringWithFormat:@"%@ 次/分",heartRate] perUnitLength:3];
            self.labRespiratoryrate.attributedText = [self setLabelText:[NSString stringWithFormat:@"%@ 次/分",breath] perUnitLength:3];
            self.labSlepp.attributedText = [self setLabelText:[NSString stringWithFormat:@"%@ 小时",sleep] perUnitLength:2];
            self.labOxygensaturation.attributedText = [self setLabelText:[NSString stringWithFormat:@"%@ %%",spo2] perUnitLength:1];
            if([skintemp intValue] > 0){
                self.labTemperature.attributedText = [self setLabelText:[NSString stringWithFormat:@"%@ ℃",skintemp] perUnitLength:1];
            }else{
                skintemp = @"0";
                self.labTemperature.attributedText = [self setLabelText:[NSString stringWithFormat:@"%@ ℃",skintemp] perUnitLength:1];
            }
            self.labDepth.text = [NSString stringWithFormat:@"%@小时",effective];
            self.labNumber.text = [NSString stringWithFormat:@"%@次",rover];
            if([activity intValue] > 0 ){
               NSString *height =  [[NSUserDefaults standardUserDefaults]objectForKey:UserHeight];
               NSString *weight = [[NSUserDefaults standardUserDefaults]objectForKey:UserWeight];
                if([[[NSUserDefaults standardUserDefaults]objectForKey:UserSex] intValue] == 0){//女
                    _distance = [activity floatValue]*(0.413)*[height floatValue]/100000;
                    _heat = [weight floatValue]*_distance*1.036;
                }else{
                    _distance = [activity floatValue]*(0.415)*[height floatValue]/100000;
                    _heat = [weight floatValue]*_distance*1.036;
                }
                self.labDistance.text = [NSString stringWithFormat:@"%.1f公里",_distance];
                self.labHeat.text = [NSString stringWithFormat:@"%.1f千卡",_heat];
            }else{
                self.labDistance.text = @"0.0公里";
                self.labHeat.text = @"0.0千卡";
            }
            self.labelTime.text =  [_response objectForKey:@"time"];
            [self.tableView reloadData];
            [SVProgressHUD dismiss];
        }else{
            [SVProgressHUD dismiss];
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW([responseObject objectForKey:@"message"]);
            }
        }
    }];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {//计步
        HealthSummaryGraphViewController *personal = [[UIStoryboard storyboardWithName:@"HealthViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"HealthSummaryGraphViewController"];
        [self.navigationController pushViewController:personal animated:YES];
    }else if (indexPath.row == 1){//睡眠
        HealthSleepingViewController *breathe = [[HealthSleepingViewController alloc] init];
        breathe.strTitle = @"睡眠";
        [self.navigationController pushViewController:breathe animated:YES];
    }else if (indexPath.row == 2){//心率
        HealthHeartRateViewController *breathe = [[HealthHeartRateViewController alloc] init];
        breathe.strTitle = @"心率";
        [self.navigationController pushViewController:breathe animated:YES];
    }else if (indexPath.row == 3){//血氧
        HealthOxygenViewController *breathe = [[HealthOxygenViewController alloc] init];
        breathe.strTitle = @"血氧";
        [self.navigationController pushViewController:breathe animated:YES];
    }else if (indexPath.row == 4){//呼吸
        HealthBreatheViewController *breathe = [[UIStoryboard storyboardWithName:@"HealthViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"HealthBreatheViewController"];
        breathe.strTitle = @"呼吸";
        [self.navigationController pushViewController:breathe animated:YES];
    }else{//体温
        HealthTemperatureViewController *breathe = [[HealthTemperatureViewController alloc]init];
        breathe.strTitle = @"体表温度";
        [self.navigationController pushViewController:breathe animated:YES];
    }
}

#pragma mark - VRGCalendarView Delegate
-(void)calendarView:(VRGCalendarView *)calendarView
    switchedToMonth:(int)month
       targetHeight:(float)targetHeight
           animated:(BOOL)animated {
}

-(void)calendarView:(VRGCalendarView *)calendarView dateSelected:(NSDate *)date {
    [self hiddenPickerView];
    self.selectDate = [NSString stringTime:date];
    [self getHealthData];
}

#pragma mark - set/get
- (NSMutableDictionary *)response{
    if (_response) {
        _response = [NSMutableDictionary dictionary];
    }
    return _response;
}

#pragma mark - 私有方法
- (NSMutableAttributedString *)setLabelText:(NSString *)text perUnitLength:(int)length{
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc]initWithString:text];
    [attributedStr addAttribute:NSFontAttributeName
                          value:[UIFont systemFontOfSize:16.0]
                          range:NSMakeRange(text.length - length, length)];
    return attributedStr;
}

- (NSString *)changeType:(NSString *)myObj{
    if([myObj isEqualToString:@"<nil>"] || myObj == nil || myObj == NULL){
        return @"0";
    }else{
        return myObj;
    }
}

#pragma 点击分享事件
//点击分享按钮
- (void)rightNavButtonClicked:(id)sender {
    _pickerView.hidden = YES;
    _maskView.hidden = YES;
    //隐藏内容视图
    //    self.contentBgView.hidden = YES;
    __weak typeof(self) weakSelf = self;
    //显示分享面板 （自定义UI可以忽略）
    [UMSocialUIManager showShareMenuViewInView:nil sharePlatformSelectionBlock:^(UMSocialShareSelectionView *shareSelectionView, NSIndexPath *indexPath, UMSocialPlatformType platformType) {
        //        [weakSelf disMissShareMenuView];
        [weakSelf shareDataWithPlatform:platformType];
        
    }];
}

//创建分享内容对象
- (UMSocialMessageObject *)creatMessageObject
{
    
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    NSString *title = @"久乐健康身体资料折线图";
    NSString *url = [NSString stringWithFormat:@"http://www.jiuletech.com/usercenter/index.php/User/Login/health_t22?id=%@1475826470", [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"]];
//    NSString *url = @"http://t.cn/Rf9TSAv";
//    NSLog(@"url:%@",url);
    NSString *text = @"久乐健康app";
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:text thumImage:@"http://www.jiuletech.com:8088/upload/share/shareimage.jpg"];
    [shareObject setWebpageUrl:url];
    messageObject.shareObject = shareObject;

    return messageObject;
}
- (void)gainScore
{
    NSMutableDictionary *params = [NSMutableDictionary new];
    int  userID = [[[NSUserDefaults standardUserDefaults]objectForKey:@"userID"]intValue];
    NSNumber *user_id = [NSNumber numberWithInt:userID];
    [params setObject:user_id forKey:@"user_id"];
    [MallRequestManager post:@"Notice/share" RequestParams:params  FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if (dic!=nil) {
            NSLog(@"dic:%@",[dic objectForKey:@"message"]);
        }
    }];
}
//直接分享
- (void)shareDataWithPlatform:(UMSocialPlatformType)platformType
{
//    UMSocialMessageObject *messageObject = nil;
//    if (platformType ==UMSocialPlatformType_Sina) {
//        NSString *title = @"test";
//        NSString *text = @"123";
//        NSString *url = @"http://t.cn/Rf9TSAv";
//        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:text thumImage:@"http://59.172.105.130:8088/upload/share/shareimage.jpg"];
//        [shareObject setWebpageUrl:url];
//        messageObject.shareObject = shareObject;
//        
//    }else
//    {
        UMSocialMessageObject *messageObject = [self creatMessageObject];
//    }
   
    //调用分享接口
    
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        NSString *message = nil;
        if (!error) {
            message = [NSString stringWithFormat:@"分享成功"];
            //获得积分
            [self gainScore];
        }
        else{
            if (error) {
                message = [NSString stringWithFormat:@"分享失败"];
            }
            else{
                message = [NSString stringWithFormat:@"分享失败"];
            }
        }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"久乐健康身体资料折线图"
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                              otherButtonTitles:nil];
        [alert show];
    }];
}

- (NSString *)timeStamp:(NSString *)strTime{
    NSTimeInterval time=[strTime doubleValue];
    NSDate*detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter*dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"YYYY年MM月dd日hh:mm"];
    NSString*currentDateStr = [dateFormatter stringFromDate:detaildate];
    return currentDateStr;
}

- (void)setupDateView:(DateType)type{
    if (_pickerView == nil) {
        _maskView = [[UIView alloc] initWithFrame:self.view.bounds];
        [_maskView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenPickerView)]];
        _maskView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.4];
        [self.view addSubview:_maskView];
        _maskView.tag = 0x22;
        _pickerView = [[VRGCalendarView alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.view.bounds)/2 - kVRGCalendarViewWidth/2, CGRectGetHeight(self.view.frame)/2 - 271 / 2, kVRGCalendarViewWidth, 0)];
        _pickerView.delegate = self;
        [self.view addSubview:_pickerView];
    } else {
        [self hiddenPickerView];
        [self.view addSubview:_pickerView];
    }
}

- (void)hiddenPickerView {
    _pickerView.hidden = !_pickerView.hidden;
    _maskView.hidden = _pickerView.hidden;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
